import subprocess
from time import sleep


def run_adb_command(ip, port, command_args):
    connect_command = f'adb connect {ip}:{port}'

    """运行ADB命令"""
    base_command = ['adb', '-s', f'{ip}:{port}']
    full_command = base_command + command_args
    try:
        subprocess.run(connect_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        result = subprocess.run(full_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return result
    except subprocess.CalledProcessError as e:
        print("An error occurred:", e.stderr)


def openApp(device_ip, device_port, package_name, activity_name):
    if is_app_install(device_ip, device_port, package_name):
        run_adb_command(ip, port, ['shell', 'am', 'start', '-n', f'{package_name}/{activity_name}'])
    else:
        print(f'{device_ip}:{device_port}这个设备未安装应用，无法打开！')
    pass


def check_app_installed(ip, port, package_name):
    try:
        # 使用 adb 命令检查应用程序包是否已安装
        result = run_adb_command(ip, port, ["shell", "pm", "list", "packages", package_name])
        # 检查输出是否包含指定的包名
        return package_name in result.stdout
    except subprocess.CalledProcessError as e:
        print(f"错误: 无法检查应用程序是否安装: {e}")
        return None


def is_app_install(device_ip, device_port, package_name):
    return check_app_installed(device_ip, device_port, package_name)


def check_phone_current_app(device_ip, device_port, activity_name):
    activity_info: str = check_phone_current_app1(device_ip, device_port)
    print(activity_info)
    index = activity_info.find(activity_name)
    return index != -1


def check_phone_current_app1(ip, port):
    result = run_adb_command(ip, port, ['shell', 'dumpsys window'])
    # 查找包含 "mCurrentFocus" 的行
    for line in result.stdout.splitlines():
        if "mCurrentFocus" in line:
            return line


if __name__ == '__main__':
    #安卓ip地址
    ip = "36.212.131.204"
    #安卓ip端口号
    port_list = [
        "40007"
    ]

    #抖音
    package_name = 'com.ss.android.ugc.aweme'
    activity_name = 'com.ss.android.ugc.aweme.splash.SplashActivity'

    #崩坏3
    # package_name = 'com.miHoYo.enterprise.NGHSoDBak'
    # activity_name = 'com.miHoYo.overridenativeactivity.OverrideNativeActivity'
    for port in port_list:
        if check_phone_current_app(ip, port, activity_name):
            print(f'端口为{port}，{activity_name}已启动，跳过执行')
        else:
            print(f"端口为{port}，正在启动{package_name}...")
            openApp(ip, port, package_name, activity_name)
            print('-----------------------------------------------')
            sleep(2)
